'''
Created on 09/04/2013

@author: tsantana
'''
from datetime import datetime

from gaesessions import get_current_session
from thilux_models import User, Menu, MenuItem
    

def is_user_logged():
    session=get_current_session()
    user = session.get('logged_user')
    
    if user:
        return True
    else:
        return False
    
def get_user():
    if is_user_logged():
        return get_current_session().get('logged_user')
    else:
        return None
    
def get_user_role():
    user=get_user()
    
    if user:
        return user.role
    else:
        return None

def gen_menu_for_user():
    '''
        This method gets the menus allowed for the user based on his role/profile and returns it with its items in a dict.
        If no menus are found, then None is returned
    '''
    session = get_current_session()
    
    if not is_user_logged():
        return None
    
    user = session.get('logged_user')
    
    if not user:
        return None
    
    menu_dict={}
    
    menus = Menu.gql('WHERE role = :1', user.role)
    
    if menus:
        for menu in menus:
            menu_items = MenuItem.gql('WHERE menu = :1', menu)
            menu_items_dict={}
            for menu_item in menu_items:
                menu_items_dict[menu_item.name]=menu_item.link
            menu_dict[menu.title]=menu_items_dict
            
        return menu_dict
            
    else:
        return None
    
def terminate_session():
    session=get_current_session()
    if session.is_active:
        session.terminate()
        
def create_session_for_user(user):
    session=get_current_session()
    session.regenerate_id()
    session['logged_user'] = user
    session['loggin_time'] = datetime.now()
    